package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.DateFormates;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.SelectCourse;
import com.example.educationalsystem.entity.Teacher;
import com.example.educationalsystem.entity.Vo.CourseVo;
import com.example.educationalsystem.entity.Vo.ScoreVo;
import com.example.educationalsystem.entity.Vo.SelectCourseVo;
import com.example.educationalsystem.entity.Vo.VoteRecordVo;
import com.example.educationalsystem.entity.VoteRecord;
import com.example.educationalsystem.service.ISelectCourseService;
import com.example.educationalsystem.service.ITeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-20
 */
@RestController
@RequestMapping("/selectCourse")
@Api(value = "/selectCourse",tags = "选课信息管理")
public class SelectCourseController {

    @Autowired
    private ISelectCourseService iSelectCourseService;
    @ApiOperation(value = "导入选课信息",notes = "导入选课信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson Import(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, SelectCourseVo.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    SelectCourse selectCourse= (SelectCourse) list.get(i);
                    System.out.println(selectCourse);
                    //使用mybatis-plus添加到数据库
                    iSelectCourseService.save(selectCourse);
                }
            }
            responseJson.setStatus(200);
            responseJson.setMsg("导入成功！");
        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg("导入失败！");
            e.printStackTrace();
        }

        return responseJson;
    }
    @ApiOperation(value = "导出所有选课信息",notes = "导出所有选课信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {

        try{
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
            EasyExcel.write(response.getOutputStream(), SelectCourseVo.class).sheet(tableName).doWrite(iSelectCourseService.getAllSelectCourse());
        }catch(Exception e)
        {
            response.reset();
        }


    }
    @GetMapping("/getAllSelectCourse")
    @ApiOperation(value = "获取所有选课信息",notes = "获取所有选课信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllSelectCourse()
    {
        ResponseJson responseJson=new ResponseJson();
        List<SelectCourseVo> selectCourselist=iSelectCourseService.getAllSelectCourse();
        if(selectCourselist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(selectCourselist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无教师信息！");
        }
        return responseJson;
    }
    @GetMapping("/getSelectCoursePage")
    @ApiOperation(value = "获取选课分页信息",notes = "获取选课分页信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getScorePage(
            @RequestParam(value = "size", defaultValue = "10") long size,
            @RequestParam(value = "current", defaultValue = "1") long current,
            String studentId,String courseId
    )
    {
        ResponseJson responseJson=new ResponseJson();
        Page<SelectCourseVo> page=new Page<>(current,size);
        QueryWrapper<SelectCourseVo> queryWrapper=new QueryWrapper<>();
        if(studentId==null&&courseId==null)
        {
            queryWrapper=null;
        }
        if(studentId!=null)
        {
            queryWrapper.eq("a.student_id",studentId);
        }

        Page<SelectCourseVo> SelectCourseVoPage=iSelectCourseService.getSelectCoursePage(page,queryWrapper);
        if(SelectCourseVoPage!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(SelectCourseVoPage);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无信息！");
        }
        return responseJson;

    }
    @ApiOperation(value = "增加选课信息",notes = "增加一条选课信息记录")
    @PostMapping("/insertSelectCourse")
    @ResponseBody
    public ResponseJson insertSelectCourse(@RequestBody SelectCourse requestSelectCourse)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<SelectCourse> selectCourseQueryWrapper=new QueryWrapper<>();
        SelectCourse selectCourse=iSelectCourseService.getBaseMapper().selectOne(selectCourseQueryWrapper.eq("student_id",requestSelectCourse.getStudentId()).eq("course_id",requestSelectCourse.getCourseId()));
        if(selectCourse==null)
        {
            Boolean result=iSelectCourseService.save(requestSelectCourse);
            if(result)
            {
                responseJson.setMsg("增加成功！");
                responseJson.setStatus(200);
                responseJson.setData(requestSelectCourse);

            }
            else
            {
                responseJson.setStatus(400);
                responseJson.setMsg("增加失败！");
            }
        }
        else {
            responseJson.setStatus(400);
            responseJson.setMsg("增加失败,重复添加!");
        }

        return responseJson;
    }

    @ApiOperation(value = "批量删除选课信息",notes = "根据选课编号，删除多条选课信息")
    @DeleteMapping("/deleteSelectCourses")
    @ResponseBody
    public  ResponseJson deleteSelectCourses( @ApiParam(name = "Ids", value = "选课IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iSelectCourseService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }

    @ApiOperation(value = "删除选课信息",notes = "根据studentID，删除一条选课信息(退选)")
    @DeleteMapping("/deleteSelectCourse")
    @ResponseBody
    public  ResponseJson deleteSelectCourse( @ApiParam(name = "courseId", value = "课程号", required = true) @RequestParam String courseId, @ApiParam(name = "studentId", value = "学号", required = true) @RequestParam String studentId)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<SelectCourse> queryWrapper=new QueryWrapper<>();
        SelectCourse selectCourseOne=iSelectCourseService.getBaseMapper().selectOne(queryWrapper.eq("course_id",courseId).eq("student_id",studentId));
        if(selectCourseOne!=null) {
            int result = iSelectCourseService.getBaseMapper().delete(queryWrapper.eq("course_id",courseId).eq("student_id",studentId));
            System.out.println(result);
            if (result == 1) {
                responseJson.setData(iSelectCourseService.getBaseMapper().selectOne(queryWrapper.eq("course_id",courseId).eq("student_id",studentId)));
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            } else {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }
        }
        else
        {
            responseJson.setMsg("该选课信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;

    }

    @ApiOperation(value = "更新选课信息",notes = "更新选课信息，必须填写studentID")
    @PutMapping("/updateSelectCourse")
    @ResponseBody
    public ResponseJson updateSelectCourse(@RequestBody  SelectCourse resquestSelectCourse)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<SelectCourse> queryWrapper=new QueryWrapper<>();
        SelectCourse selectCourseOne=iSelectCourseService.getBaseMapper().selectOne(queryWrapper.eq("student_id",resquestSelectCourse.getStudentId()));
        if(selectCourseOne!=null)
        {
            int result=iSelectCourseService.getBaseMapper().update(resquestSelectCourse,queryWrapper.eq("student_id",resquestSelectCourse.getStudentId()));
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(resquestSelectCourse);
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("该选课信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }

}

